<template>
  <div class="app-container">
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="queryParams.username" placeholder="用户名" clearable @keyup.enter="handleQuery" />
        </el-form-item>

        <el-form-item label="真实姓名" prop="name">
          <el-input v-model="queryParams.name" placeholder="真实姓名" clearable @keyup.enter="handleQuery" />
        </el-form-item>

        <el-form-item label="所属角色" prop="roleIds">
          <el-select v-model="queryParams.roleIds" placeholder="选择所属角色" clearable>
            <el-option v-for="item in roleOptions" :key="item.roleId" :label="item.roleName" :value="item.roleId" />
          </el-select>
        </el-form-item>

        <el-form-item label="账号类型" prop="type">
          <el-select v-model="queryParams.type" class="small" placeholder="全部" clearable>
            <el-option label="内部账号" :value="1" />
            <el-option label="外部账号" :value="2" />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <template #icon><ep-Search /></template>
            搜索
          </el-button>
          <el-button @click="handleResetQuery">
            <template #icon><ep-Refresh /></template>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <template #header>
        <div class="flex-x-b">
          <el-button type="success" @click="handleOpenDialog()">
            <template #icon><ep-Plus /></template>
            新增
          </el-button>
          <el-button @click="handleOpenImportDialog">
            <template #icon><ep-Upload /></template>
            导入
          </el-button>
        </div>
      </template>

      <el-table v-auto-h v-loading="loading" :data="pageData" border>
        <el-table-column key="username" label="用户名" align="center" prop="username" width="200" />
        <el-table-column label="真实姓名" align="center" prop="name" width="120" />

        <el-table-column label="所属角色" align="center" prop="roleNames" />

        <el-table-column label="账号类型" width="100" align="center" prop="type">
          <template #default="{ row }">
            <span>{{ row.type === 1 ? '内部账号' : '外部账号' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="手机号码" align="center" prop="phone" width="120" />

        <el-table-column label="状态" align="center" prop="lockFlag" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.lockFlag == '0' ? 'success' : 'info'">
              {{ scope.row.lockFlag == '0' ? '正常' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="180" />
        <!-- <el-table-column label="更新时间" align="center" prop="updateTime" width="180" /> -->
        <el-table-column label="操作" fixed="right" width="220">
          <template #default="{ row }">
            <el-button type="primary" size="small" link @click="handleOpenAssignPermDialog(row)">
              <template #icon><ep-Position /></template>
              数据权限
            </el-button>
            <el-button type="primary" link size="small" @click="handleOpenDialog(row)">
              <template #icon><ep-Edit /></template>
              编辑
            </el-button>
            <el-button type="danger" link size="small" @click="handleDelete(row.userId)">
              <template #icon><ep-Delete /></template>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-model:page="current" v-model:pagesize="pageSize" :total="total" />
    </el-card>

    <!-- 用户表单弹窗 -->
    <el-drawer v-model="drawer.visible" :title="drawer.title" append-to-body @close="handleCloseDialog">
      <el-form ref="userFormRef" :model="formData" :rules="rules" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <!-- <el-input v-model="formData.username" :readonly="!!formData.userId" placeholder="请输入用户名" /> -->
          <el-select
            v-model="formData.username"
            value-key="username"
            filterable
            remote
            placeholder="请输入用户名"
            :remote-method="queryUsername"
            :no-data-text="queryUsernameText"
            :disabled="!!formData.userId"
            @change="changeUserName"
          >
            <el-option v-for="item of usernameDatas" :key="item.username" :value="item.username" :label="item.username" />
          </el-select>
        </el-form-item>

        <el-form-item label="真实姓名" prop="name">
          <el-input v-model="formData.name" placeholder="请输入真实姓名" />
        </el-form-item>

        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="formData.phone" placeholder="请输入手机号码" maxlength="11" />
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="formData.email" placeholder="请输入邮箱" maxlength="50" />
        </el-form-item>

        <el-form-item label="角色" prop="roleIdArray">
          <el-select v-model="formData.roleIdArray" multiple filterable placeholder="请选择">
            <el-option v-for="item in roleOptions" :key="item.roleId" :label="item.roleName" :value="item.roleId" />
          </el-select>
        </el-form-item>

        <el-form-item label="账号类型" prop="type">
          <el-radio-group v-model="formData.type">
            <el-radio border :value="1">内部账号</el-radio>
            <el-radio border :value="2">外部账号</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="状态" prop="lockFlag" size="large">
          <el-switch
            v-model="formData.lockFlag"
            size="large"
            inline-prompt
            active-text="正常"
            inactive-text="禁用"
            active-value="0"
            inactive-value="9"
          />
        </el-form-item>
        <el-alert v-if="formData.lockFlag === '9'" type="warning" show-icon :closable="false">
          <span>处于“禁用”状态的账户，禁止使用混凝土物流调度系统的全部功能</span>
        </el-alert>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-drawer>

    <!-- 分配权限弹窗 -->
    <el-dialog v-model="assignPermVisible" title="搅拌站权限分配" width="520px" @close="handleCloseAssignPermDialog">
      <div class="flex-y-c mr-30 mb-20">
        <span>启用状态：</span>
        <el-switch v-model="mixingStationChecked" />
      </div>
      <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" :disabled="!mixingStationChecked" @change="handleCheckAllChange">
        全选
      </el-checkbox>
      <el-checkbox-group
        v-model="checkedMixingStations"
        class="pb-10"
        :disabled="!mixingStationChecked"
        @change="handleCheckedMixingStationChange"
      >
        <el-checkbox v-for="item in mixingStations" :key="item.id" :label="item.name" :value="item.number">
          {{ item.name }}
        </el-checkbox>
      </el-checkbox-group>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" :loading="assignPermSubmitLoading" @click="handleAssignPermSubmit">确 定</el-button>
          <el-button @click="handleCloseAssignPermDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <Import
      v-model="importDialogVisible"
      action="upms/user/importUser"
      template-action="upms/resources/template/user_template.xlsx"
      @import-success="handleQuery"
    />
  </div>
</template>

<script lang="ts" setup>
import { useRequest, usePagination } from '@/hooks/useRequest'
import { getUserPage, addUser, editUser, deleteUser, getUserDataAuth, editUserDataAuth, queryIDaasUser } from '@/api/system/user'
import { getMixingStationList } from '@/api/customer/customer'
import { getAllRole } from '@/api/system/role'
import { useThrottleFn } from '@vueuse/core'
import type { UserPageQuery, UserPageData, UserForm } from '@/api/system/user'
import type { FormInstance } from 'element-plus'

const queryFormRef = ref<FormInstance>()
const userFormRef = ref<FormInstance>()

const queryParams = ref<UserPageQuery>({ nowPage: 1, pageSize: 10 })

const formData = reactive<UserForm>({
  lockFlag: '0',
  type: 1
})

const drawer = reactive({
  visible: false,
  title: ''
})

const usernameDatas = ref([])
const queryUsernameText = ref('无数据')
const checkedUserId = ref<string>('')
const assignPermSubmitLoading = ref(false)
const assignPermVisible = ref(false)
const checkAll = ref(false)
const isIndeterminate = ref(false)
const checkedMixingStations = ref<string[]>([])
const mixingStationChecked = ref(false)

const importDialogVisible = ref(false)

const rules = reactive({
  username: [{ required: true, message: '用户名不能为空', trigger: 'blur' }],
  name: [{ required: true, message: '真实姓名不能为空', trigger: 'blur' }],
  roleIdArray: [{ required: true, message: '用户角色不能为空', trigger: 'blur' }],
  email: [
    {
      required: true,
      pattern: /\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}/,
      message: '请输入正确的邮箱地址',
      trigger: 'blur'
    }
  ],
  phone: [
    {
      required: true,
      pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
      message: '请输入正确的手机号码',
      trigger: 'blur'
    }
  ]
})

const { data, loading, run, total, current, pageSize } = usePagination(getUserPage, { defaultParams: [queryParams.value] })

const { data: rolesData } = useRequest(getAllRole)

const { data: mixingStationData } = useRequest(getMixingStationList, { defaultParams: [{ authFilter: false }] })

const pageData = computed(() => {
  const userDatas = data.value?.result.records || []
  // 生成 roleIdArray: 角色ID集合； roleNames: 角色名称,多个使用英文逗号(,)分割
  userDatas.map(item => {
    if (item.roleList && item.roleList.length > 0) {
      const names: string[] = []
      item.roleIdArray = []
      for (const role of item.roleList) {
        names.push(role.roleName)
        item.roleIdArray.push(role.roleId)
      }
      item.roleNames = names.join(',')
    }
    return item
  })
  return userDatas
})

const roleOptions = computed(() => rolesData.value?.result || [])

const mixingStations = computed(() => mixingStationData.value?.result || [])

const handleQuery = () => {
  run(queryParams.value)
}

const handleResetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

const queryUsername = (username: string) => {
  // if (username.length < 3) {
  //   queryUsernameText.value = '请至少输入3个字符'
  //   usernameDatas.value = []
  //   return
  // }

  queryUsernameText.value = '加载中...'

  queryIDaasUser(username).then(res => {
    const { result } = res
    usernameDatas.value = result ? [result] : []
    queryUsernameText.value = '无数据'
  })
}

const changeUserName = (val: string) => {
  if (val) {
    const findUser = usernameDatas.value[0] // 已知后端只会返回一个数据，所以这里直接取第一个
    formData.name = findUser.realName
    formData.phone = findUser.mobile
    formData.email = findUser.email
  }
}

const handleOpenAssignPermDialog = async (row: UserPageData) => {
  assignPermVisible.value = true
  checkedUserId.value = row.userId

  // 回显用户已拥有的搅拌站权限
  getUserDataAuth(row.userId).then(data => {
    const permData = data.result && data.result.length > 0 ? data.result[0] : undefined
    if (permData) {
      mixingStationChecked.value = permData.status === 1
      if (permData.mixingStationCodes) {
        checkedMixingStations.value = permData.mixingStationCodes.split(',')
        const checkedCount = checkedMixingStations.value.length
        checkAll.value = checkedCount === mixingStations.value.length
        isIndeterminate.value = checkedCount > 0 && checkedCount < mixingStations.value.length
      }
    }
  })
}

const handleCloseAssignPermDialog = () => {
  assignPermVisible.value = false
  checkedUserId.value = ''
  checkAll.value = false
  isIndeterminate.value = false
  mixingStationChecked.value = false
  checkedMixingStations.value = []
}

const handleCheckAllChange = (val: any) => {
  checkedMixingStations.value = val ? mixingStations.value.map(item => item.number) : []
  isIndeterminate.value = false
}

const handleCheckedMixingStationChange = (value: any) => {
  const checkedCount = value.length
  checkAll.value = checkedCount === mixingStations.value.length
  isIndeterminate.value = checkedCount > 0 && checkedCount < mixingStations.value.length
}

const handleAssignPermSubmit = () => {
  const userId = checkedUserId.value
  if (userId) {
    assignPermSubmitLoading.value = true
    const data = {
      userId,
      mixingStationCodes: checkedMixingStations.value.join(','),
      type: 3, // 3 搅拌站业务
      status: mixingStationChecked.value ? 1 : 0 // 1 启用 0 禁用
    }
    editUserDataAuth(data)
      .then(() => {
        ElMessage.success('分配权限成功')
        assignPermVisible.value = false
        handleQuery()
      })
      .finally(() => {
        assignPermSubmitLoading.value = false
      })
  }
}

async function handleOpenDialog(row?: UserPageData) {
  drawer.visible = true
  if (row) {
    drawer.title = '修改用户'
    await nextTick()
    const data = { ...row }
    delete data.roleList
    delete data.roleNames
    Object.assign(formData, data)
  } else {
    drawer.title = '新增用户'
  }
}

const handleCloseDialog = () => {
  userFormRef.value.resetFields()
  userFormRef.value.clearValidate()

  drawer.visible = false

  formData.userId = undefined
  formData.lockFlag = '0'
  formData.type = 1
  formData.roleIds = ''
}

const handleSubmit = useThrottleFn(() => {
  userFormRef.value.validate(valid => {
    if (valid) {
      const userId = formData.userId
      loading.value = true
      formData.roleIds = formData.roleIdArray.join(',')
      if (userId) {
        editUser(formData)
          .then(() => {
            ElMessage.success('修改用户成功')
            handleCloseDialog()
            handleQuery()
          })
          .finally(() => (loading.value = false))
      } else {
        addUser(formData)
          .then(() => {
            ElMessage.success('新增用户成功')
            handleCloseDialog()
            handleQuery()
          })
          .finally(() => (loading.value = false))
      }
    }
  })
}, 3000)

const handleDelete = (userId?: string) => {
  ElMessageBox.confirm('确认删除用户?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(function () {
    loading.value = true
    deleteUser(userId)
      .then(() => {
        ElMessage.success('删除成功')
        handleQuery()
      })
      .finally(() => (loading.value = false))
  })
}

const handleOpenImportDialog = () => {
  importDialogVisible.value = true
}
</script>
<style lang="scss" scoped></style>
